package com.zws.cucumber.spring;

import com.zws.cucumber.ZwsConstants;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * author: zws
 */
public class ZwsCxfApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        setProperty(applicationContext, "local.server.port", ZwsConstants.JETTY_PORT);
        setProperty(applicationContext, "wiremock.unreachablePort", ZwsConstants.WIREMOCK_UNREACHABLE_PORT);

        initializeCustomizedProperties(applicationContext);

        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        propertySourcesPlaceholderConfigurer.setEnvironment(applicationContext.getEnvironment());
        applicationContext.addBeanFactoryPostProcessor(propertySourcesPlaceholderConfigurer);
    }

    protected void initializeCustomizedProperties(ConfigurableApplicationContext applicationContext) {

    }

    protected void setProperty(ApplicationContext context, String propertyName, Object propertyValue) {
        if (context instanceof ConfigurableApplicationContext) {
            setProperty(((ConfigurableApplicationContext) context).getEnvironment(), propertyName, propertyValue);
        }
        if (context.getParent() != null) {
            setProperty(context.getParent(), propertyName, propertyValue);
        }
    }

    @SuppressWarnings("unchecked")
    private void setProperty(ConfigurableEnvironment environment, String propertyName, Object propertyValue) {
        MutablePropertySources sources = environment.getPropertySources();
        PropertySource<?> source = sources.get("component-test");
        if (source == null) {
            source = new MapPropertySource("component-test", new HashMap<>());
            sources.addFirst(source);
        }
        ((Map<String, Object>) source.getSource()).put(propertyName, propertyValue);
    }
}
